#include "mainwindow.h"
#include "ui_mainwindow.h"

// https://www.jb51.net/article/182743.htm

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow), thread(nullptr) {
    ui->setupUi(this);

    worker = new Worker;

    qDebug() << "主线程" << QThread::currentThreadId();

    connect(worker, &Worker::msg2, this, &MainWindow::msg2Slot);
    connect(this, &MainWindow::msg3, worker, &Worker::msg3Slot);
}

MainWindow::~MainWindow() {
    delete ui;
    delete worker;
}

void MainWindow::on_pushButtonStart_clicked() {
    qDebug() << "on_pushButtonStart_clicked线程" << QThread::currentThreadId();
    if (thread)
        return;

    thread = new QThread;
    worker->moveToThread(thread);

    QObject::connect(thread, &QThread::started, worker, &Worker::workSlot);

    QObject::connect(thread, &QThread::finished, this,
                     &MainWindow::workerDetach);

    thread->start();
}

void MainWindow::on_pushButtonStop_clicked() {
    qDebug() << "on_pushButtonStop_clicked线程" << QThread::currentThreadId();

    if (thread) {
        thread->quit();
        thread->wait();
        delete thread;
        thread = nullptr;
    }
}

void MainWindow::on_pushButtonMsg1_clicked() {
    qDebug() << "on_pushButtonMsg1_clicked线程" << QThread::currentThreadId();

    emit worker->msg1("消息1哦");
}

void MainWindow::on_pushButtonMsg2_clicked() {
    qDebug() << "on_pushButtonMsg2_clicked线程" << QThread::currentThreadId();

    emit worker->msg2("消息2啊！！！");
}

void MainWindow::on_pushButtonMsg3_clicked() {
    qDebug() << "on_pushButtonMsg2_clicked线程" << QThread::currentThreadId();

    emit msg3("这是消息3呀呀呀！");
}

void MainWindow::workerDetach() {
    qDebug() << "workerDetach线程" << QThread::currentThreadId();
    worker->moveToThread(QThread::currentThread());
}

void MainWindow::msg2Slot(const QString &m2) {
    qDebug() << "msg2Slot线程" << QThread::currentThreadId() << "收到消息"
             << m2;
}
